package com.zdp.nio.reactor.handle;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * 读取客户端数据，回显到客户端
 */
public class EchoHandler implements Runnable{

    private SocketChannel channel;
    final SelectionKey sk;

    private Selector selector;

    final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    static final int RECIEVING = 0, SENDING = 1;
    int state = RECIEVING;

    public EchoHandler(Selector s,SocketChannel c) throws IOException {
        this.selector = s;
        this.channel = c;
        channel.configureBlocking(false);
        sk = channel.register(selector, SelectionKey.OP_READ);
        sk.attach(this);
        selector.wakeup();
    }


    @Override
    public void run() {
        try{
            if(state == RECIEVING){
                // 从通道中读取数据
                int length = 0;
                while((length = channel.read(byteBuffer)) > 0){
                    System.out.println(new String(byteBuffer.array(),0,length));
                }
                // 切换为读取
                byteBuffer.flip();
                // 监听事件转换为 写入就绪
                sk.interestOps(SelectionKey.OP_WRITE);
                // 进入写入状态
                state = SENDING;
            }else if(state == SENDING){
                // 将byteBuffer中的数据写入到通道
                channel.write(byteBuffer);
                // 切换为写入模式
                byteBuffer.clear();
                // 修改 监听事件,(read 就绪事件)
                sk.interestOps(SelectionKey.OP_READ);
                // 进入接收状态
                state = RECIEVING;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
